package root.service;

import common.MonitorTcpDataPackage;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.function.Consumer;
import java.util.logging.Logger;

public class MonitorSocketConnection {

    Logger log=Logger.getLogger("MonitorSocketConnection");
    Socket socket;
    private static MonitorSocketConnection monitorSocketConnection;

    private MonitorSocketConnection(){}

    public static MonitorSocketConnection getInstance(){
        if (monitorSocketConnection==null){
            synchronized (MonitorSocketConnection.class){
                monitorSocketConnection=new MonitorSocketConnection();
            }
        }
        return monitorSocketConnection;
    }

    public void connect(){
        try {
            socket=new Socket("localhost",1280);//服务端地址和端口
        } catch (IOException e) {
            log.warning("连接socket失败："+e.getMessage());
            e.printStackTrace();
        }
    }

    public void sendData(MonitorTcpDataPackage dataPackage){
        sendData(dataPackage,null);
    }
    public MonitorTcpDataPackage getDataPackage(MonitorTcpDataPackage dataPackage){
        connect();
        try {
            var socketOutputStream=socket.getOutputStream();
            var oos = new ObjectOutputStream(socketOutputStream);
            oos.writeObject(dataPackage);
            oos.flush();
            var resultInputStream=socket.getInputStream();
            var resultPackage=(MonitorTcpDataPackage) new ObjectInputStream(resultInputStream).readObject();
            socket.shutdownOutput();
            return resultPackage;
        } catch (ClassNotFoundException e) {
            log.warning("转换消息失败："+e.getMessage());
            e.printStackTrace();
        } catch (Exception e){
            log.warning("发送数据包失败："+e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
    public void sendData(MonitorTcpDataPackage dataPackage, Consumer<MonitorTcpDataPackage> consumer){
        connect();
        try {
            var socketOutputStream=socket.getOutputStream();
            var oos = new ObjectOutputStream(socketOutputStream);
            oos.writeObject(dataPackage);
            oos.flush();
            var resultInputStream=socket.getInputStream();
            if (consumer!=null&&resultInputStream!=null){
                var resultPackage=(MonitorTcpDataPackage) new ObjectInputStream(resultInputStream).readObject();
                consumer.accept(resultPackage);
            }
            socket.shutdownOutput();
        } catch (ClassNotFoundException e) {
            log.warning("转换消息失败："+e.getMessage());
            e.printStackTrace();
        } catch (Exception e){
            log.warning("发送数据包失败："+e.getMessage());
            e.printStackTrace();
        }
    }
}
